﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;
using System.ComponentModel;
using System.Windows.Data;
using System.Windows.Threading;

using PermDoc.Ctrl.Docs;

namespace PermDoc
{

    public partial class PageFavorites : Page, INotifyPropertyChanged
    {

        #region Members
        private bool IsInit = false;
        public event PropertyChangedEventHandler PropertyChanged;
        private Object ApplayFilterLock = new Object();
        private Object GridRefreshLock = new Object();
        private long _invalidateFireCount = 0;
        protected static DispatcherTimer _timer_Refresh = new DispatcherTimer();
        protected static bool IsRefresh = false;
        protected static DispatcherTimer _timer_idle = new DispatcherTimer();
        private Uri _WelcomeUri = new Uri(@"/Welcome.xaml", UriKind.Relative);
        private Uri _DocUri = new Uri(@"/PageDoc.xaml", UriKind.Relative);
        #endregion

        #region Constructors
        public PageFavorites()
        {
            InitializeComponent();
            _timer_Refresh.Tick += new EventHandler(myTimer_GetDataTick);
            _timer_Refresh.Interval = new TimeSpan(0, 0, 1);
        }
        #endregion

        #region Page Events
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }
        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            App.IdleEmpty();
            IsRefresh = true;
            App.PageFavoritesPtr = this;
            App.ListView_Favorites = new PagedCollectionView(App.Topics_CurDay);
            gv.ItemsSource = App.ListView_Favorites;
            if (gv.Columns.Count > 0)
            {
                foreach (DataGridColumn c in gv.Columns)
                {
                    if (c.Header.ToString() == "ChildTopics")
                        c.Visibility = Visibility.Collapsed;
                }
            }
            FilterApplay();
            IsRefresh = false;

            _timer_idle.Tick += new EventHandler(myTimer_Idle);
            _timer_idle.Interval = new TimeSpan(0, 0, 1);
            _timer_idle.Start();

            IsInit = true;
        }
        private void Page_Unloaded(object sender, RoutedEventArgs e)
        {
            _timer_idle.Stop();
            _timer_Refresh.Stop();
            App.PageFavoritesPtr = null;
            App.ListView_Favorites = null;
            gv.ItemsSource = null;
            IsInit = false;
        }
        void myTimer_GetDataTick(object sender, EventArgs e)
        {
            if (_invalidateFireCount>0)
                myInvalidateData();
            _timer_Refresh.Stop();
            IsRefresh = false;
            gv.IsEnabled = true;
        }
        private void Page_MouseMove(object sender, MouseEventArgs e)
        {
            App.IdleEmpty();
            if (App.isProcessGetData == false)
                gv.Visibility = System.Windows.Visibility.Visible;
            else
                gv.Visibility = System.Windows.Visibility.Collapsed;
        }
        private void Page_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            App.IdleEmpty();
            if (App.isProcessGetData == false)
                gv.Visibility = System.Windows.Visibility.Visible;
            else
                gv.Visibility = System.Windows.Visibility.Collapsed;
        }
        private void Page_MouseRightButtonUp(object sender, MouseButtonEventArgs e)
        {
            App.IdleEmpty();
            if (App.isProcessGetData == false)
                gv.Visibility = System.Windows.Visibility.Visible;
            else
                gv.Visibility = System.Windows.Visibility.Collapsed;
        }
        private void Page_MouseWheel(object sender, MouseWheelEventArgs e)
        {
            App.IdleEmpty();
            if (App.isProcessGetData == false)
                gv.Visibility = System.Windows.Visibility.Visible;
            else
                gv.Visibility = System.Windows.Visibility.Collapsed;
        }
        private void Page_KeyUp(object sender, KeyEventArgs e)
        {
            App.IdleEmpty();
        }
        void myTimer_Idle(object sender, EventArgs e)
        {
            if (App.Idle > App._idleMax)
            {
                if (App.MainPagePtr.navFrame.Source != _WelcomeUri)
                {
                    App.MainPagePtr.navFrame.Source = _WelcomeUri;
                }
            }
            else
            {
                if (App.isProcessGetData == false)
                    gv.Visibility = System.Windows.Visibility.Visible;
                else
                    gv.Visibility = System.Windows.Visibility.Collapsed;
            }
        }
        #endregion

        #region Controls Events
        private void gv_MouseMove(object sender, MouseEventArgs e)
        {
            App.IdleEmpty();
        }
        private void gv_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            App.IdleEmpty();
        }
        private void gv_MouseRightButtonUp(object sender, MouseButtonEventArgs e)
        {
            App.IdleEmpty();
        }
        private void gv_MouseWheel(object sender, MouseWheelEventArgs e)
        {
            App.IdleEmpty();
        }
        protected void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
        private void oFavoritesCheck_Checked(object sender, RoutedEventArgs e)
        {
            if (_invalidateFireCount > 0)
                _invalidateFireCount--;
            if (IsRefresh == true)
                return;
            lock (GridRefreshLock)
            {
                CheckBox o = (sender as CheckBox);
                if (o != null)
                {
                    Topic topic = ((System.Windows.FrameworkElement)(o)).DataContext as Topic;
                    if (topic != null)
                    {
                        //topic.NotifyPropertyChanged("FavoritesValue");
                        //topic.NotifyPropertyChanged("IsFavorites");
                    }
                }
                //o.Dispatcher.BeginInvoke(delegate { o.UpdateLayout(); });
                if (IsRefresh == false && _invalidateFireCount <= 0)
                {
                    gv.IsEnabled = false;
                    IsRefresh = true;
                    _invalidateFireCount++;
                    _timer_Refresh.Start();
                }
            }
        }
        private void oFavoritesCheck_Unchecked(object sender, RoutedEventArgs e)
        {
            if (_invalidateFireCount > 0)
                _invalidateFireCount--;
            //if (IsRefresh == true)
            //    return;
            lock (GridRefreshLock)
            {
                CheckBox o = (sender as CheckBox);
                if (o != null)
                {
                    Topic topic = ((System.Windows.FrameworkElement)(o)).DataContext as Topic;
                    if (topic != null)
                    {
                        if (topic.FavoritesValue != 0)
                        {
                            topic.FavoritesValue = 0;
                            //topic.NotifyPropertyChanged("FavoritesValue");
                            //topic.NotifyPropertyChanged("IsFavorites");
                        }
                    }
                }
                //o.Dispatcher.BeginInvoke(delegate { o.UpdateLayout(); });
                if (IsRefresh == false && _invalidateFireCount <= 0)
                {
                    gv.IsEnabled = false;
                    IsRefresh = true;
                    _invalidateFireCount++;
                    _timer_Refresh.Start();
                }
            }
        }
        private void OnoFavoritesValueChanged(object sender, RoutedPropertyChangedEventArgs<double?> e)
        {
            if(_invalidateFireCount > 0)
                _invalidateFireCount--;
            if (IsRefresh == true)
                return;
            lock (GridRefreshLock)
            {
                System.Windows.Controls.Rating o = sender as System.Windows.Controls.Rating;
                if (o != null)
                {
                    Topic topic = ((System.Windows.FrameworkElement)(o)).DataContext as Topic;
                    if (topic != null)
                    {
                        topic.FavoritesValue = o.Value ?? 0;
                        //topic.NotifyPropertyChanged("FavoritesValue");
                        //topic.NotifyPropertyChanged("IsFavorites");
                    }
                }
                //o.Dispatcher.BeginInvoke(delegate { o.UpdateLayout(); });
                if (IsRefresh == false && _invalidateFireCount <= 0)
                {
                    gv.IsEnabled = false;
                    IsRefresh = true;
                    _invalidateFireCount++;
                    _timer_Refresh.Start();
                }
            }
        }
        private void oBtnClearAll_Click(object sender, RoutedEventArgs e)
        {
            App.ClearFavoritesAll();
            lock (ApplayFilterLock)
            {
                this.gv.ItemsSource = null;
                App.ListView_Favorites = new PagedCollectionView(App.Topics_CurDay);
                this.gv.ItemsSource = App.ListView_Favorites;
                PagedCollectionView pcv = this.gv.ItemsSource as PagedCollectionView;
                pcv.Filter = new Predicate<object>(FilterFavoritesMethod);
            }
        }
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Topic sel = (Topic)gv.SelectedItem;
            if (sel != null)
            {
                App.SelectedDocumentTopic = new Topic(sel);
                App.MainPagePtr.navFrame.Source = _DocUri;
            }
        }
        #endregion

        #region Data
        protected void myInvalidateData()
        {
            lock (GridRefreshLock)
            {
                //this.gv.InvalidateArrange();
                this.gv.ItemsSource = null;
                this.gv.ItemsSource = App.ListView_Favorites;
                this.FilterApplay();
                _timer_Refresh.Stop();
            }
        }
        public void FilterApplay()
        {
            if (gv.ItemsSource == null)
                return;
            lock (ApplayFilterLock)
            {
                PagedCollectionView pcv = this.gv.ItemsSource as PagedCollectionView;
                pcv.Filter = new Predicate<object>(FilterFavoritesMethod);
            }
        }
        public bool FilterFavoritesMethod(object t)
        {
            if (t == null)
                return false;
            Topic o = t as Topic;
            return (o.IsFavorites == true);
        }
        #endregion        

    }
}
